package com.bbcare.followup.plat.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.OSSClientUtil;
import com.bbcare.comm.PropertiesUtils;
import com.bbcare.comm.ResultModel;
import com.bbcare.comm.SeqUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.department.plat.entity.DepartmentBasic;
import com.bbcare.department.plat.service.IDepartmentBasicService;
import com.bbcare.followup.plat.entity.FollowQueue;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.entity.PatientQueueScheme;
import com.bbcare.followup.plat.entity.PatientTask;
import com.bbcare.followup.plat.entity.PtEvaluationGuide;
import com.bbcare.followup.plat.entity.PtEvaluationResult;
import com.bbcare.followup.plat.service.IFollowEvaluationService;
import com.bbcare.followup.plat.service.IFollowQueueService;
import com.bbcare.followup.plat.service.IPatientService;
import com.bbcare.followup.plat.service.IPatientqueryCardService;
import com.bbcare.followup.plat.store.ibatis.IConfCacheDAO;
import com.bbcare.followup.plat.store.ibatis.IFollowQueueDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientQueueSchemeDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskDAO;

@Controller
@RequestMapping("/webapi/service")
public class AppWomanController {
	Logger logger = Logger.getLogger(PatientqueryCardController.class);

	@Autowired
	private IPatientService patientSerivce;

	@Autowired
	private IFollowQueueService followQueueService;

	@Autowired
	private IFollowQueueDAO followQueueDAO;

	@Autowired
	private IPatientqueryCardService patientqueryCardService;

	@Autowired
	private IPatientQueueSchemeDAO patientQueueSchemeDao;

	@Autowired
	IPatientDAO patientdao;

	@Autowired
	private IPatientTaskDAO patientTaskDao;

	@Autowired
	private IFollowEvaluationService followEvaluationService;

	@Autowired
	private IDepartmentBasicService deparmentBasicService;

	@Autowired
	private IConfCacheDAO iConfCacheDAO;

	// 某个队列建档问卷查询
	@ResponseBody
	@RequestMapping("/appContentQuery")
	public ResultModel<Map<String, Object>> appContentQuery(@RequestBody String arg) throws Exception {
		logger.warn("in appContentQuery----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		String channel = jsonData.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}

		Map<String, Object> retMap = new HashMap<String, Object>();
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		String schemeId = jsonData.getString("followSchemeId");
		String queueId = jsonData.getString("followQueueId");

		Map<String, Object> MapIn = new HashMap<String, Object>();
		MapIn.put("id", queueId);
		List<FollowQueue> followQueue = followQueueDAO.selectById(MapIn);
		if (StringUtils.isBlank(schemeId)) {
			// 队列下无应用方案，直接返回
			if (!CollectionUtils.isEmpty(followQueue)) {
				schemeId = followQueue.get(0).getSchemeId();
			}
		}
		paramMap.put("schemeId", schemeId);
		paramMap.put("queueId", queueId);

		retMap = followQueueService.qryQueueSchemePatientAddContent(paramMap);

		return new ResultModel<Map<String, Object>>(retMap);
	}

	// 患者添加
	@ResponseBody
	@RequestMapping("/register/CreateUser")
	public ResultModel<Map<String, Object>> CreateUser(@RequestBody String arg, HttpServletRequest request)
			throws Exception {
		logger.warn("in CreateUser----arg==" + arg.toString());

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}
		String currTime = jsonData.getString("opTime");// 入参中有操作时间，则使用入参中的时间
		if (StringUtils.isBlank(currTime)) {
			currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
		}
		String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水

		String channel = jsonData.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}

		// 参数校验后续补充
		String queueId = jsonData.getString("followQueueId");
		if (StringUtils.isBlank(queueId)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入队列id或值为空！"));
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", queueId);
		FollowQueue queue = followQueueService.getQueueDetailByQueueId(map);
		if (null == queue) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "根据队列id查询无此队列信息！"));
		}
		String queueUserType = queue.getQueueUsertype();

		Map<String, Object> servParamMap = jsonData;

		String author = "自主建档";
		String authorName = "自主建档";// 登录账号医生姓名
		String tenantId = "";// 租户id
		String deptId = "";// 科室
		if (StringUtils.isBlank(deptId)) {
			deptId = queue.getDeptId();
		}
		if (StringUtils.isBlank(tenantId)) {
			tenantId = queue.getTenantId();
		}
		String opCode = jsonData.getString("opCode");
		String opType = jsonData.getString("opType");
		if (StringUtils.isBlank(opCode)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，操作编码为空！"));
		}
		if (StringUtils.isBlank(opType)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，操作类型为空！"));
		}
		if (StringUtils.isBlank(jsonData.getString("opNote"))) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，操作备注为空！"));
		}
		String userType = jsonData.getString("userType");
		if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
			// 孕产妇（母亲），暂时写死，回头完善
			userType = "2";
		} else if (StringUtils.isBlank(userType)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，患者类型为空！"));
		}

		// 入参中没有，从问卷答案中获取
		Map<String, Object> quesMap = (JSONObject) jsonData.getJSONObject("questiones");

		String phoneNum = jsonData.getString("phoneNo");
		if (StringUtils.isBlank(phoneNum)) {
			if (null != quesMap && 0 != quesMap.size()) {
				phoneNum = (String) quesMap.get(Constants.QUESTION_ID_FOR_PHONENO);
				if (StringUtils.isBlank(phoneNum)) {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "手机号码不能为空！"));
				}
			}
		}
		phoneNum = phoneNum.trim();
		String patientName = jsonData.getString("patientName");
		if (StringUtils.isBlank(patientName)) {
			if (null != quesMap && 0 != quesMap.size()) {
				patientName = (String) quesMap.get(Constants.QUESTION_ID_FOR_PATIENTNAME);
				if (StringUtils.isBlank(patientName)) {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "患者姓名不能为空！"));
				}
			}
		}
		patientName = patientName.trim();
		String gender = jsonData.getString("gender");
		if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
			// 孕产妇（母亲）
			gender = Constants.GENDER_FOR_FEMALE;
		} else if (StringUtils.isBlank(gender)) {
			if (null != quesMap && 0 != quesMap.size()) {
				gender = (String) quesMap.get(Constants.QUESTION_ID_FOR_GENDER);
				if (StringUtils.isBlank(gender)) {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "性别不能为空！"));
				}
			}
		}
		gender = gender.trim();
		// 转换性别
		if (Constants.GENDER_ALIAS_FOR_MALE.equals(gender)) {
			gender = Constants.GENDER_FOR_MALE;
		} else if (Constants.GENDER_ALIAS_FOR_FEMALE.equals(gender)) {
			gender = Constants.GENDER_FOR_FEMALE;
		} else if (!Constants.GENDER_FOR_MALE.equals(gender) && !Constants.GENDER_FOR_FEMALE.equals(gender)) {
			gender = Constants.GENDER_FOR_MALE;
		}

		 // 末次月经日期
        String lastMenstruationDate = (String) quesMap.get(Constants.QUESTION_ID_FOR_LAST_MENSTRUATION_DATE);
        if (StringUtils.isBlank(lastMenstruationDate)) {
            // 不在这里校验，在实例化随访任务时校验
        } else {
            servParamMap.put("lastMenstruationDate", lastMenstruationDate);
        }

		String birthday = jsonData.getString("birthday");
		if (StringUtils.isBlank(birthday)) {
			if (null != quesMap && 0 != quesMap.size()) {
				birthday = (String) quesMap.get(Constants.QUESTION_ID_FOR_BIRTHDAY);
				if (StringUtils.isBlank(birthday) && !Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "出生日期不能为空！"));
				}
			}
		}
		// 预产期
		String expectedDay = jsonData.getString("expectedDay");
		if (StringUtils.isBlank(expectedDay)) {
			if (null != quesMap && 0 != quesMap.size()) {
				expectedDay = (String) quesMap.get(Constants.QUESTION_ID_FOR_EXPECTEDDAY);
			}
		}
		if (StringUtils.isEmpty(expectedDay)) {
			expectedDay = null;
		}

		// 出生胎龄(孕周)
		int pregnancyDay = 0;
		// 直接从入参中获取
		if (null != jsonData.getInteger("pregnancyWeek")) {
			pregnancyDay = jsonData.getIntValue("pregnancyWeek");
		}
		// 再考虑从问卷中获取，问卷存储格式：[39,5]
		if (pregnancyDay <= 0 && !MapUtils.isEmpty(quesMap)) {
			String preStr = (String) quesMap.get(Constants.QUESTION_ID_FOR_PREGNANCYDAY);
			if (!StringUtils.isBlank(preStr)) {
				String preArr[] = preStr.split(Constants.COMMA_SPLIT_STR);
				if (null != preArr && 2 == preArr.length) {
					String preWeekStr = preArr[0].substring(1);
					String preDayStr = preArr[1].substring(0, preArr[1].length() - 1);
					int preWeek = Integer.parseInt(preWeekStr);
					int preDay = Integer.parseInt(preDayStr);
					pregnancyDay = preWeek * Constants.PREGNANCY_CALC_UNIT_WEEK + preDay;
				}
			}
		}
		// 最后根据根据生日和预产期计算
		String babybitrhday = jsonData.getString("babybitrhday");
		if (pregnancyDay <= 0 && !StringUtils.isBlank(expectedDay)) {
			pregnancyDay = ToolUtils.calPrenDayByBirthAndExpect(babybitrhday, expectedDay);
		}

		// 孕周未填，默认280
		if (pregnancyDay <= 0) {
			pregnancyDay = Constants.PATIENT_NORMAL_PREGNANT_DAY;
		}
		// 预产期未填，默认与出生日期一致
		if (StringUtils.isBlank(expectedDay)) {
			expectedDay = birthday;
		}

		if (pregnancyDay > 300) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
					"尊敬的用户，您填写的出生日期或者预产期不正确，请检查！");
		}
		Patient pt = new Patient();
		pt.setPregnancyDay(pregnancyDay);
		pt.setUserName(patientName);
		pt.setPhoneNo(phoneNum);
		pt.setFirstName(patientName.substring(0, 1));
		pt.setCreateTime(currTime);
		pt.setUpdateTime(currTime);
		pt.setCreateAuthor(author);
		pt.setBirthday(birthday);
		pt.setExpectedDay(expectedDay);
		pt.setGender(gender);
		pt.setUserType(userType);
		pt.setSourceType(opType);
		servParamMap.put("patient", pt);
		servParamMap.put("authorName", authorName);
		servParamMap.put("deptId", deptId);
		servParamMap.put("queueId", queueId);
		servParamMap.put("updateTime", currTime);
		servParamMap.put("authorId", author);
		servParamMap.put("updateAccept", updateAccept);
		servParamMap.put("tenantId", tenantId);
		servParamMap.put("opCode", opCode);
		servParamMap.put("opNote", jsonData.getString("opNote"));
		servParamMap.put("opType", opType);
		servParamMap.put("contentData", jsonData.getJSONObject("questiones"));

		// 先根据微信号 租户下是否建过用户
		Map<String, Object> qryPtMap = new HashMap<String, Object>();
		qryPtMap.put("phoneNo", phoneNum);
		// qryPtMap.put("wechat_id", openId);
		qryPtMap.put("tenantId", tenantId);
		qryPtMap.put("userType", "2");
		List<Patient> ptList = patientdao.selectByPhoneNo(qryPtMap);

		String userId = "";
		Map<String, Object> ptMap = new HashMap<String, Object>();
		if (!CollectionUtils.isEmpty(ptList)) {
			userId = ptList.get(0).getId();
		}
		ptMap.put("userId", userId);
		ptMap.put("tenantId", tenantId);
		ptMap.put("queueId", queueId);
		List<String> statulist = new ArrayList<String>();
		statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
		ptMap.put("status", statulist);
		List<PatientQueueScheme> queueSchemeList = patientQueueSchemeDao.selectByUserId(ptMap);
		String ptSchemeId = "";
		Map<String, Object> userMap = new HashMap<String, Object>();
		if (CollectionUtils.isEmpty(queueSchemeList)) {
			// 对应一个租户下的一个类型的用户信息 ---产妇或宝宝
			userMap = patientSerivce.registerPatient(servParamMap);
			ptSchemeId = (String) userMap.get("ptSchemeId");
			userId = (String) userMap.get("patientId");
		} else {
			// 更新建档信息
			ptSchemeId = queueSchemeList.get(0).getId();
			ptMap.clear();
			ptMap.put("seqNo", Constants.TASK_SEQ_FOR_INIT);
			ptMap.put("ptSchemeId", ptSchemeId);
			// 查询taskid
			List<PatientTask> taskList = patientTaskDao.select(ptMap);
			String taskId = "";
			if (!CollectionUtils.isEmpty(taskList)) {
				taskId = taskList.get(0).getId();
			}
			servParamMap.put("ptSchemeId", ptSchemeId);
			servParamMap.put("userId", userId);
			servParamMap.put("taskId", taskId);
			servParamMap.put("type", Constants.QUESTIONNAIRE_TYPE_0);
			patientSerivce.modTaskContentData(servParamMap);
			userMap.put("ptSchemeId", ptSchemeId);
			userMap.put("patientId", userId);
		}

		return new ResultModel<Map<String, Object>>(userMap);
	}

	// 查询用户信息
	@ResponseBody
	@RequestMapping("/queryUserMassage")
	public ResultModel<Map<String, Object>> queryUserMassage(@RequestBody String arg) throws Exception {
		logger.warn("in queryUserMassage----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		String channel = jsonData.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}

		String phoneNo = jsonData.getString("phoneNo");
		if (StringUtils.isBlank(phoneNo)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，服务号码为空！"));
		}

		Map<String, Object> retMap = new HashMap<String, Object>();
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		String schemeId = jsonData.getString("followSchemeId");
		String queueId = jsonData.getString("followQueueId");

		Map<String, Object> MapIn = new HashMap<String, Object>();
		MapIn.put("id", queueId);
		String tenantId = "";
		String userType = Constants.PTUSER_PATIENT_USER_TYPE_BABY;
		List<FollowQueue> followQueue = followQueueDAO.selectById(MapIn);
		if (StringUtils.isBlank(schemeId)) {
			// 队列下无应用方案，直接返回
			if (!CollectionUtils.isEmpty(followQueue)) {
				schemeId = followQueue.get(0).getSchemeId();
				tenantId = followQueue.get(0).getTenantId();
				String queueUserType = followQueue.get(0).getQueueUsertype();
				if (Constants.QUEUE_USER_TYPE_PARTURIENT.equals(queueUserType)) {
					// 孕产妇（母亲），暂时写死，回头完善
					userType = Constants.PTUSER_PATIENT_USER_TYPE_PARTURIENT;
				}else if(Constants.QUEUE_USER_TYPE_OTHER.equals(queueUserType)) {
					userType = Constants.PTUSER_PATIENT_USER_TYPE_OTHER;
				}
			}
		}

		paramMap.put("schemeId", schemeId);
		paramMap.put("queueId", queueId);
		paramMap.put("tenantId", tenantId);
		paramMap.put("phoneNo", phoneNo);
		paramMap.put("userName",jsonData.getString("userName"));
		paramMap.put("userType",userType);

		retMap = patientqueryCardService.queryUserMassage(paramMap);
		if(StringUtils.isBlank((String)retMap.get("userId"))) {
			retMap.put("userId", SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_USERID));
		}
		return new ResultModel<Map<String, Object>>(retMap);
	}

	// 患者添加,辅助生殖用户添加
	@ResponseBody
	@RequestMapping("GfyPatientAdd")
	public ResultModel<List<Map<String, Object>>> GfyPatientAdd(@RequestBody String arg, HttpServletRequest request)
			throws Exception {
		logger.warn("in GfyPatientAdd----arg==" + arg.toString());
		List<Map<String, Object>> listOut = new ArrayList<Map<String, Object>>();
		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		String channel = jsonData.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}

		// 参数校验后续补充
		String queueId = jsonData.getString("followQueueId");
		if (StringUtils.isBlank(queueId)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入队列id或值为空！"));
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", queueId);
		FollowQueue queue = followQueueService.getQueueDetailByQueueId(map);
		if (null == queue) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "根据队列id查询无此队列信息！"));
		}
		String queueUserType = queue.getQueueUsertype();

		String motherhash = jsonData.getString("motherhash");
		if (StringUtils.isBlank(motherhash)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
					"入参节点错误，未传入产妇识别id或值为空！"));
		}

		Map<String, Object> servParamMap = jsonData;

		String author = "自主建档";
		String authorName = "自主建档";// 登录账号医生姓名
		String tenantId = "";// 租户id
		String deptId = "";// 科室
		if (StringUtils.isBlank(deptId)) {
			deptId = queue.getDeptId();
		}
		if (StringUtils.isBlank(tenantId)) {
			tenantId = queue.getTenantId();
		}
		String opCode = jsonData.getString("opCode");
		String opType = jsonData.getString("opType");
		if (StringUtils.isBlank(opCode)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，操作编码为空！"));
		}
		if (StringUtils.isBlank(opType)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，操作类型为空！"));
		}
		if (StringUtils.isBlank(jsonData.getString("opNote"))) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，操作备注为空！"));
		}
		String userType = jsonData.getString("userType");
		if (StringUtils.isBlank(userType)) {
			userType = queueUserType;
		}

		// 入参中没有，从问卷答案中获取
		Map<String, Object> quesMap = (JSONObject) jsonData.getJSONObject("questiones");

		String phoneNum = jsonData.getString("phoneNo");
		if (StringUtils.isBlank(phoneNum)) {
			if (null != quesMap && 0 != quesMap.size()) {
				phoneNum = (String) quesMap.get(Constants.QUESTION_ID_FOR_PHONENO);
				if (StringUtils.isBlank(phoneNum)) {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "手机号码不能为空！"));
				}
			}
		}
		phoneNum = phoneNum.trim();
		// 预产期
		String expectedDay = jsonData.getString("expectedDay");
		if (StringUtils.isBlank(expectedDay)) {
			if (null != quesMap && 0 != quesMap.size()) {
				expectedDay = (String) quesMap.get(Constants.QUESTION_ID_FOR_EXPECTEDDAY);
			}
		}
		if (StringUtils.isEmpty(expectedDay)) {
			expectedDay = null;
		}

		// 出生胎龄(孕周)
		int pregnancyDay = 0;
		String patientName = "";
		String birthday = "";
		String gender = "";
		String idCard = "";
		// 直接从入参中获取
		if (null != jsonData.getInteger("pregnancyWeek")) {
			pregnancyDay = jsonData.getIntValue("pregnancyWeek");
		}
		// 再考虑从问卷中获取，问卷存储格式：[39,5]
		if (pregnancyDay <= 0 && !MapUtils.isEmpty(quesMap)) {
			String preStr = (String) quesMap.get(Constants.QUESTION_ID_FOR_PREGNANCYDAY);
			if (!StringUtils.isBlank(preStr)) {
				String preArr[] = preStr.split(Constants.COMMA_SPLIT_STR);
				if (null != preArr && 2 == preArr.length) {
					String preWeekStr = preArr[0].substring(1);
					String preDayStr = preArr[1].substring(0, preArr[1].length() - 1);
					int preWeek = Integer.parseInt(preWeekStr);
					int preDay = Integer.parseInt(preDayStr);
					pregnancyDay = preWeek * Constants.PREGNANCY_CALC_UNIT_WEEK + preDay;
				}
			}
		}

		List<Map<String, Object>> babyList = new ArrayList<Map<String, Object>>();
		String updateAccept = "";
		Map<String, Object> motherMap = new HashMap<String, Object>();
		motherMap = ToolUtils.typeCast(jsonData.getJSONObject("extendInfo"));
		if (motherMap == null || motherMap.size() <= 0) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "母亲信息不能为空！"));
		}

		Map<String,Object> mapinfo = new HashMap<String,Object>();
		mapinfo.put("type","1110");
		mapinfo.put("paramCode","gfy10101");
		List<Map<String,Object>> list = iConfCacheDAO.selectBsStaticParamByTypeAndCode(mapinfo);
		List<String> listkey = new ArrayList<String>();
		listkey.add(motherMap.get("motherName").toString());
		babyList = ToolUtils.typeCast(jsonData.getJSONArray("babyList"));
		if (babyList != null && babyList.size() > 0) {
			for (int i = 0; i < babyList.size(); i++) {
				Map<String, Object> userMap = new HashMap<String, Object>();
				updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
				String currTime = jsonData.getString("opTime");// 入参中有操作时间，则使用入参中的时间
				if (StringUtils.isBlank(currTime)) {
					currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
				}
				Patient pt = new Patient();
				patientName = (String) babyList.get(i).get("babyname");
				if (StringUtils.isBlank(patientName)) {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "宝宝姓名不能为空！"));
				}

				birthday = (String) babyList.get(i).get("babybirthday");
				if (StringUtils.isBlank(birthday)) {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "宝宝生日不能为空！"));
				}

				idCard = (String) babyList.get(i).get("idIccid");

				gender = (String) babyList.get(i).get("gender");
				if (StringUtils.isBlank(gender)) {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "宝宝性别不能为空！"));
				}

				String babyhash = (String) babyList.get(i).get("babyhash");

				// 最后根据根据生日和预产期计算
				if (pregnancyDay <= 0 && !StringUtils.isBlank(expectedDay)) {
					pregnancyDay = ToolUtils.calPrenDayByBirthAndExpect(birthday, expectedDay);
				}

				// 孕周未填，默认280
				if (pregnancyDay <= 0) {
					pregnancyDay = Constants.PATIENT_NORMAL_PREGNANT_DAY;
				}
				// 预产期未填，默认与出生日期一致
				if (StringUtils.isBlank(expectedDay)) {
					expectedDay = birthday;
				}
				pt.setPregnancyDay(pregnancyDay);
				pt.setUserName(patientName);
				pt.setPhoneNo(phoneNum);
				pt.setFirstName(patientName.substring(0, 1));
				pt.setCreateTime(currTime);
				pt.setUpdateTime(currTime);
				pt.setCreateAuthor(author);
				pt.setBirthday(birthday);
				pt.setExpectedDay(expectedDay);
				pt.setGender(gender);
				pt.setUserType(userType);
				pt.setSourceType(opType);
				pt.setIdCard("");

				Map<String, Object> mapIn1 = new HashMap<String, Object>();
				mapIn1.put(Constants.QUESTION_ID_FOR_PHONENO, phoneNum);
				mapIn1.put(Constants.QUESTION_ID_FOR_PATIENTNAME, patientName);
				mapIn1.put(Constants.QUESTION_ID_FOR_GENDER, gender);
				mapIn1.put(Constants.QUESTION_ID_FOR_BIRTHDAY, birthday);
				mapIn1.put(Constants.QUESTION_ID_FOR_IDCARD, idCard);
				if(list!=null && list.size()>0) {
					for(int j=0;j<list.size();j++) {
						mapIn1.put((String) list.get(j).get("PARAM_VALUE"), listkey.get(j));
					}
				}
				servParamMap.put("contentData", JSON.toJSON(mapIn1));

				servParamMap.put("patient", pt);
				servParamMap.put("authorName", authorName);
				servParamMap.put("deptId", deptId);
				servParamMap.put("queueId", queueId);
				servParamMap.put("updateTime", currTime);
				servParamMap.put("authorId", author);
				servParamMap.put("updateAccept", updateAccept);
				servParamMap.put("tenantId", tenantId);
				servParamMap.put("opCode", opCode);
				servParamMap.put("opNote", jsonData.getString("opNote"));
				servParamMap.put("opType", opType);
				servParamMap.put("extendInfo", jsonData.getJSONObject("extendInfo"));// 问卷答案

				List<Patient> ptList = null;
				String userId = (String) babyList.get(i).get("userId");
				;
				// 先根据微信号 租户下是否建过用户
				if (StringUtils.isBlank(userId)) {
					Map<String, Object> qryPtMap = new HashMap<String, Object>();
					qryPtMap.put("phoneNo", phoneNum);
					qryPtMap.put("userName", patientName);
					qryPtMap.put("tenantId", tenantId);
					qryPtMap.put("userType", "1");
					ptList = patientdao.selectByPhoneNo(qryPtMap);
					if (!CollectionUtils.isEmpty(ptList)) {
						userId = ptList.get(0).getId();
					}
				}
				Map<String, Object> ptMap = new HashMap<String, Object>();
				ptMap.put("userId", userId);
				ptMap.put("tenantId", tenantId);
				ptMap.put("queueId", queueId);
				List<String> statulist = new ArrayList<String>();
				statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
				ptMap.put("status", statulist);
				List<PatientQueueScheme> queueSchemeList = patientQueueSchemeDao.selectByUserId(ptMap);
				String ptSchemeId = "";
				Map<String, Object> retMap = new HashMap<String, Object>();
				retMap.put("babyName", patientName);
				retMap.put("motherhash", motherhash);
				retMap.put("babyidcard", idCard);
				retMap.put("queueId", queueId);

				if (CollectionUtils.isEmpty(queueSchemeList)) {
					// 对应一个租户下的一个类型的用户信息 ---产妇或宝宝
					userId = "";
					userMap = patientSerivce.registerPatient(servParamMap);
					retMap.put("userId", userMap.get("patientId"));
					Map<String, Object> mapOut = patientqueryCardService.bindWomenBaby(retMap);
					userMap.put("babyhash", mapOut.get("babyhash"));
				} else {
					// 更新建档信息
					Map<String, Object> mapIn = new HashMap<String, Object>();
					mapIn.put(Constants.QUESTION_ID_FOR_PHONENO, phoneNum);
					mapIn.put(Constants.QUESTION_ID_FOR_PATIENTNAME, patientName);
					mapIn.put(Constants.QUESTION_ID_FOR_GENDER, gender);
					mapIn.put(Constants.QUESTION_ID_FOR_BIRTHDAY, birthday);
					mapIn.put(Constants.QUESTION_ID_FOR_IDCARD, idCard);
					if(list!=null && list.size()>0) {
						for(int j=0;j<list.size();j++) {
							mapIn.put((String) list.get(j).get("PARAM_VALUE"), listkey.get(j));
						}
					}
					ptSchemeId = queueSchemeList.get(0).getId();
					ptMap.clear();
					ptMap.put("seqNo", Constants.TASK_SEQ_FOR_INIT);
					ptMap.put("ptSchemeId", ptSchemeId);
					// 查询taskid
					List<PatientTask> taskList = patientTaskDao.select(ptMap);
					String taskId = "";
					if (!CollectionUtils.isEmpty(taskList)) {
						taskId = taskList.get(0).getId();
					}
					servParamMap.put("ptSchemeId", ptSchemeId);
					servParamMap.put("userId", userId);
					servParamMap.put("taskId", taskId);
					servParamMap.put("type", Constants.QUESTIONNAIRE_TYPE_0);
					servParamMap.put("contentData", JSON.toJSON(mapIn));
					logger.info("contentData" + mapIn.toString());
					patientSerivce.modTaskContentData(servParamMap);
					if (StringUtils.isBlank(babyhash)) {
						retMap.put("userId", userId);
						Map<String, Object> mapOut = patientqueryCardService.bindWomenBaby(retMap);
						userMap.put("babyhash", mapOut.get("babyhash"));
					} else {
						userMap.put("babyhash", babyhash);
					}
					userMap.put("ptSchemeId", ptSchemeId);
					userMap.put("patientId", userId);
					userId = "";
				}
				listOut.add(userMap);
			}

		} else {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "宝宝信息不能为空！"));
		}

		if (pregnancyDay > 300) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
					"尊敬的用户，您填写的出生日期或者预产期不正确，请检查！");
		}

		return new ResultModel<List<Map<String, Object>>>(listOut);
	}

	// 查询用户信息
	@ResponseBody
	@RequestMapping("/queryBaby")
	public ResultModel<Map<String, Object>> queryBaby(@RequestBody String arg) throws Exception {
		logger.warn("in queryBaby-----arg==" + arg);

		JSONObject jsonArg = null;
		try {
			jsonArg = JSON.parseObject(arg);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
		}

		JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
		if (null == jsonData) {
			// 前台必须传data节点，否则报错返回
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
		}

		String channel = jsonData.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}

		String phoneNo = jsonData.getString("phoneNo");
		if (StringUtils.isBlank(phoneNo)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，服务号码为空！"));
		}

		String motherName = jsonData.getString("motherName");
		if (StringUtils.isBlank(motherName)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，产妇名称为空！"));
		}

		Map<String, Object> retMap = new HashMap<String, Object>();
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		String schemeId = jsonData.getString("followSchemeId");
		String queueId = jsonData.getString("followQueueId");

		Map<String, Object> MapIn = new HashMap<String, Object>();
		MapIn.put("id", queueId);
		String tenantId = "";
		List<FollowQueue> followQueue = followQueueDAO.selectById(MapIn);
		if (StringUtils.isBlank(schemeId)) {
			// 队列下无应用方案，直接返回
			if (!CollectionUtils.isEmpty(followQueue)) {
				schemeId = followQueue.get(0).getSchemeId();
				tenantId = followQueue.get(0).getTenantId();
			}
		}
		paramMap.put("schemeId", schemeId);
		paramMap.put("queueId", queueId);
		paramMap.put("tenantId", tenantId);
		paramMap.put("phoneNo", phoneNo);
		paramMap.put("motherName", motherName);

		retMap = patientqueryCardService.queryBaby(paramMap);

		return new ResultModel<Map<String, Object>>(retMap);
	}

	// 解绑产妇和宝宝的关系
	@ResponseBody
	@RequestMapping("/unbindWomenBaby")
	public ResultModel<Map<String, Object>> unbindWomenBaby(HttpServletRequest request, @RequestBody String jsonStr)
			throws Exception {
		logger.info("in unbindWomenBaby----arg==" + jsonStr);
		JSONObject jsonEsb = JSON.parseObject(jsonStr);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理

		if (null == requestParam) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		String channel = requestParam.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}

		String babyName = requestParam.getString("babyName");
		if (StringUtils.isEmpty(babyName)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，宝宝姓名不能为空!");
		}

		String userId = requestParam.getString("userId");
		if (StringUtils.isEmpty(userId)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，用户id不能为空!");
		}

		String queueId = requestParam.getString("queueId");
		if (StringUtils.isEmpty(queueId)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，队列id不能为空!");
		}

		String motherhash = requestParam.getString("motherhash");

		if (StringUtils.isEmpty(motherhash)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，产妇识别码不能为空!");
		}

		String babyhash = requestParam.getString("babyhash");
		if (StringUtils.isEmpty(babyhash)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，宝宝识别码不能为空!");
		}

		Map<String, Object> retMap = new HashMap<String, Object>();
		Map<String, Object> paramMap = new LinkedHashMap<String, Object>();

		paramMap.put("babyName", babyName);
		paramMap.put("motherhash", motherhash);
		paramMap.put("babyhash", babyhash);
		paramMap.put("queueId", queueId);
		paramMap.put("userId", userId);

		retMap = patientqueryCardService.unbindWomenBaby(paramMap);

		return new ResultModel<Map<String, Object>>(retMap);

	}

	// 解绑产妇和宝宝的关系
	@ResponseBody
	@RequestMapping("/bindWomenBaby")
	public ResultModel<Map<String, Object>> bindWomenBaby(HttpServletRequest request, @RequestBody String jsonStr)
			throws Exception {
		logger.info("in unbindWomenBaby----arg==" + jsonStr);
		JSONObject jsonEsb = JSON.parseObject(jsonStr);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理

		if (null == requestParam) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		String channel = requestParam.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}

		String babyName = requestParam.getString("babyName");
		if (StringUtils.isEmpty(babyName)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，宝宝姓名不能为空!");
		}

		String userId = requestParam.getString("userId");
		if (StringUtils.isEmpty(userId)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，用户id不能为空!");
		}

		String queueId = requestParam.getString("queueId");
		if (StringUtils.isEmpty(queueId)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，队列id不能为空!");
		}

		String motherhash = requestParam.getString("motherhash");

		if (StringUtils.isEmpty(motherhash)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，产妇识别码不能为空!");
		}

		Map<String, Object> retMap = new HashMap<String, Object>();
		Map<String, Object> paramMap = new LinkedHashMap<String, Object>();

		paramMap.put("babyName", babyName);
		paramMap.put("motherhash", motherhash);
		paramMap.put("queueId", queueId);
		paramMap.put("userId", userId);

		retMap = patientqueryCardService.bindWomenBaby(paramMap);

		return new ResultModel<Map<String, Object>>(retMap);

	}

	// 用户签名保存签名图片信息
	@ResponseBody
	@RequestMapping("/sign/signature")
	public ResultModel<Map<String, Object>> signature(@RequestBody String arg, HttpServletRequest request)
			throws Exception {
		logger.info("in signature----arg==" + arg);
		JSONObject jsonEsb = JSON.parseObject(arg);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
		if (null == requestParam) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
		String examinationPaperName = requestParam.getString("evaluationType");
		if (StringUtils.isEmpty(examinationPaperName)) {
			logger.info("out getScore----arg== null");
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
					"入参校验失败，evaluationType不能为空");
		}

		/* channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆 */
		String channel = requestParam.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}

		String queueId = requestParam.getString("queueId");
		if (StringUtils.isEmpty(queueId)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "队列ID不能为空!");
		}

		String deptId = requestParam.getString("deptId");
		if (StringUtils.isEmpty(deptId)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "随访科室ID不能为空!");
		}

		String userId = requestParam.getString("userId");
		if (StringUtils.isEmpty(userId)) {
			logger.info("out evaluationType----arg== null");
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，患者id不能为空");
		}
		String sourseType = requestParam.getString("sourseType");
		List<PtEvaluationGuide> guideList = new ArrayList<PtEvaluationGuide>();

		String postionIds = requestParam.getString("postionIds");
		String taskId = requestParam.getString("taskId");
		if (StringUtils.isEmpty(postionIds)) {
			logger.info("out evaluationType----arg== null");
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，postionIds不能为空");
		}
		DepartmentBasic depObj = deparmentBasicService.getDepartmentBasicDetails(deptId);
		if (null == depObj) {
			throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DEPARTMENT_NOT_EXIST, "科室信息不存在");
		}
		String tenantId = depObj.getTenantId();// 租户id
		Map<String, Object> ptMap = new HashMap<String, Object>();
		ptMap.put("userId", userId);
		ptMap.put("tenantId", tenantId);
		Patient pt = patientSerivce.getPatient(ptMap);
		if (pt == null) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "患者信息不存在");
		}
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("examinationPaperName", examinationPaperName);
		paramMap.put("userId", userId);
		Map<String, Object> outMap = followEvaluationService.selectGmsResultDetail(paramMap);
		if (!outMap.isEmpty()) {
			@SuppressWarnings("unchecked")
			List<Map<String,Object>> list = (List<Map<String, Object>>) outMap.get("result");
			if(list!=null&&list.size()>0) {
				paramsMap = list.get(0);
			}else {
				// 问卷结果保存入库
				PtEvaluationResult answer = new PtEvaluationResult();
				String testTime = DateUtil.getDate_8(new Date());

				answer.setType(examinationPaperName);
				answer.setId(SeqUtil.getSeqNo());
				answer.setCreateTime(DateUtil.getSysDateA());
				answer.setScore(postionIds);
				answer.setResult(postionIds);
				answer.setQueueId(queueId);
				if (StringUtils.isEmpty(sourseType)) {
					answer.setSourcetype(Constants.SOURCE_TYPE_WECHAT); // APP或微信录入
				} else {
					answer.setSourcetype(sourseType); // APP或微信录入
				}

				answer.setSourceid(userId);
				answer.setTenantId(tenantId);
				answer.setUserId(userId);
				answer.setTaskId(taskId);
				answer.setTestTime(testTime);
				answer.setQueueId(queueId);
				followEvaluationService.savePtEvaluationResult(answer, guideList);
			}

		} else {
			// 问卷结果保存入库
			PtEvaluationResult answer = new PtEvaluationResult();
			String testTime = DateUtil.getDate_8(new Date());

			answer.setType(examinationPaperName);
			answer.setId(SeqUtil.getSeqNo());
			answer.setCreateTime(DateUtil.getSysDateA());
			answer.setScore(postionIds);
			answer.setResult(postionIds);
			if (StringUtils.isEmpty(sourseType)) {
				answer.setSourcetype(Constants.SOURCE_TYPE_WECHAT); // APP或微信录入
			} else {
				answer.setSourcetype(sourseType); // APP或微信录入
			}

			answer.setSourceid(userId);
			answer.setTenantId(tenantId);
			answer.setUserId(userId);
			answer.setTaskId(taskId);
			answer.setTestTime(testTime);
			answer.setQueueId(queueId);
			followEvaluationService.savePtEvaluationResult(answer, guideList);
		}
		return new ResultModel<Map<String, Object>>(paramsMap);
	}

	 /**
     * 签名上传
     *
     * @param response
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/sign/uploadSign")
    public ResultModel<Object> uploadSign(HttpServletResponse response, HttpServletRequest request)
            throws Exception {
        String filepath = "";
        String deptId = request.getParameter("deptId");
        if(StringUtils.isBlank(deptId)) {
        	deptId =PropertiesUtils.getProperty("signdeptid");
        }
        DepartmentBasic depObj = deparmentBasicService.getDepartmentBasicDetails(deptId);
		if (null == depObj) {
			throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DEPARTMENT_NOT_EXIST, "科室信息不存在");
		}
		String tenantId = depObj.getTenantId();// 租户id
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile(iter.next());
                if (!file.isEmpty()) {
                	 // 文件上传路径：基础路径+租户id
                    String  uploadPath = ToolUtils.getUploadFilePath(Constants.FILE_UPLOAD_FOR_IMG_BASIC_PATH_ID_NAME, tenantId);
                    filepath = OSSClientUtil.uploadPictureNew(file, uploadPath,false);// 保存图片
                }
            }
        }
        return new ResultModel<Object>(filepath);
    }

    // 获取文件访问url签名
    @ResponseBody
    @RequestMapping("/getImgFileSignUrl")
    public ResultModel<Object> getImgFileSignUrl(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.warn("in getImgFileSignUrl----arg==" + arg);

        // 基础校验
        ToolUtils.checkInputRoot(arg);

        JSONObject jsonArg = JSON.parseObject(arg);
        Map<String, Object> mapIn = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);

        // 操作信息校验
        List<Object> fileList = ToolUtils.typeCast(mapIn.get("fileList"));
        // 逐个获取签名
        int f = 0;
        int fsize = fileList.size();
        String imgNewUrl = "";
        String imgUrl = "";
        Map<String, Object> urlMap = new HashMap<String, Object>();
        for (f = 0; f < fsize; f++) {
            urlMap = ToolUtils.typeCast(fileList.get(f));
            imgUrl = (String) urlMap.get("imgUrl");
            imgNewUrl = OSSClientUtil.getFileSignUrl(imgUrl);
            if (StringUtils.isBlank(imgNewUrl)) {
                imgNewUrl = imgUrl;
            }
            urlMap.put("imgNewUrl", imgNewUrl);
        }

        return new ResultModel<Object>(mapIn);
    }


    // 查询建档问卷信息
    @ResponseBody
    @RequestMapping("/getPatientAddQuestion")
    public ResultModel<Object> getPatientAddQuestion(@RequestBody String arg, HttpServletRequest request) throws Exception {
    	logger.info("in getPatientAddQuestion----arg==" + arg);
		JSONObject jsonEsb = JSON.parseObject(arg);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理

		if (null == requestParam) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		String channel = requestParam.getString("channel");
		if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}

		String queueId = requestParam.getString("queueId");
		if (StringUtils.isEmpty(queueId)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，队列id不能为空!");
		}

		Map<String, Object> retMap = new HashMap<String, Object>();
		Map<String, Object> paramMap = new LinkedHashMap<String, Object>();

		paramMap.put("id", queueId);

		retMap = patientqueryCardService.getPatientAddQuestion(paramMap);

		return new ResultModel<Object>(retMap);
    }

}
